import { useState, useCallback } from "react";
import { useCookies } from "react-cookie";
import { stAPI } from "@/api";
import { TOKEN } from "@/constants/cookies";
import { useNavigate } from "react-router-dom";

export const useST = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [cookies] = useCookies([TOKEN]);
  const navigate = useNavigate();

  const hasToken = !!cookies.access_token;

  /**
   * 通过access_token获取ST并跳转到service
   */
  const getSTAndRedirect = useCallback(
    async (service?: string): Promise<boolean> => {
      setIsLoading(true);
      setError(null);

      try {
        // 获取ST
        const response = await stAPI.getST(service);

        if (response.code === 200 && response.data.ticket) {
          const st = response.data.ticket;

          // 构建重定向URL
          const redirectUrl =
            service || `${window.location.origin}/cas/profile`;
          const currentUrl = new URL(redirectUrl);
          currentUrl.searchParams.set("ticket", st);
          navigate(currentUrl.pathname + currentUrl.search);
          return true;
        } else {
          setError(response.message || "Failed to get ST");
          return false;
        }
      } catch (err: unknown) {
        const errorMessage =
          err instanceof Error ? err.message : "Failed to get ST";
        setError(errorMessage);
        return false;
      } finally {
        setIsLoading(false);
      }
    },
    [navigate]
  );

  /**
   * 清除错误
   */
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  return {
    hasToken,
    getSTAndRedirect,
    isLoading,
    error,
    clearError,
  };
};
